package notes.java.java8.demo;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

// 新日期 
// 旧的日期存在线程安全问题
public class K10_TestNewTime {

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		DateFormatThreadLocal dftl = new DateFormatThreadLocal();
		
		Callable<Date> callable = new Callable<Date>() {
			@Override
			public Date call() throws Exception {
				//return sdf.parse("2017-03-12"); // 存在线程安全问题
				return dftl.conver("2017-03-12"); // 之前解决方案
			}
		};
		
		List<Future<Date>> resList = new ArrayList<>();
		// 创建一个大小为10的线程池
		ExecutorService pool = Executors.newFixedThreadPool(20);
		for(int i=0; i<20; i++) {
			resList.add(pool.submit(callable));
		}
		
		for(Future<Date> d : resList) {
			System.out.println(d.get());
		}
		
		pool.shutdown();
	}
	
}

// 解决线程安全问题
class DateFormatThreadLocal {
	private static final ThreadLocal<DateFormat> format = new ThreadLocal<DateFormat>() {
		protected DateFormat initialValue() {
			return new SimpleDateFormat("yyyy-MM-dd");
		};
	};
	
	public static Date conver(String date) throws ParseException {
		return format.get().parse(date);
	}
}
